import useAuthStore from '@/store/authStore';
import axios from 'axios';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Login.module.css'; // 使用CSS Modules导入样式
interface LoginProps {
  onLoginSuccess: () => void;
}
const Login: React.FC<LoginProps> = ({ onLoginSuccess }) => {
  const [username, setUsername] = useState(''); // 用户名或邮箱的状态
  const [password, setPassword] = useState(''); // 密码的状态
  const [error, setError] = useState(''); // 错误信息的状态
  const navigate = useNavigate(); // 用于页面跳转的导航函数
  const setAccessToken = useAuthStore((state) => state.setAccessToken); // 从store获取设置token的方法

  const handleSubmit = async (e) => {
    e.preventDefault(); // 阻止表单的默认提交行为

    try {
      console.log('Sending login request to first API...');
      const response1 = await axios.post('http://localhost:8082/api/login', {
        username,
        password
      }, {
        headers: {
          'Content-Type': 'application/json'
        }
      });

      console.log('First API response:', response1);
      if (response1.data.status === "success") {
        console.log('First API login successful:', response1.data.message);
        const token = response1.data.data.token;
        localStorage.setItem('token', token);
        console.log('Token saved:', token);

        try {
          console.log('Sending login request to second API...');
          const response2 = await axios.post('http://127.0.0.1:7860/api/v1/login', 
            `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
            {
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': '*/*',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
              }
            }
          );

          console.log('Second API response:', response2);
          if (response2.status === 200) {
            console.log('Second API login successful');
            const accessToken = response2.data.access_token;
            console.log('Access Token:', accessToken);
            localStorage.setItem('access_token', accessToken);
            setAccessToken(accessToken); // 使用Zustand store来保存token
            onLoginSuccess();
            console.log('Access token saved:', accessToken);
          } else {
            console.error('Failed to login with the second API:', response2.status, response2.statusText);
            setError('第二个API的登录失败，请稍后再试。');
          }
        } catch (error) {
          console.error('Error logging in to the second API:', error);
          setError('第二个API的请求失败，请稍后再试。');
        }

        console.log('Navigating to select-organization page...');
      } else {
        console.error('First API login failed:', response1.data.message);
        setError(response1.data.message);
      }
    } catch (error) {
      console.error('Error logging in:', error);
      setError('登录失败，请稍后再试。');
    }
  };

  const handleRegisterClick = () => {
    console.log('Navigating to register page...');
    navigate('/register'); // 跳转到注册页面
  };
  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginBox}>
        <div className={styles.loginImage}>
          <div className={styles.logoAndText}>
            <img src="/1.jpg" alt="Logo" className={styles.logoImg} />
            <h1>智链iLink</h1>
          </div>
          <img src="/yhtx_dlzc_1.png" alt="iLink" className={styles.mainImg} />
        </div>
        <div className={styles.verticalLine}></div>
        <div className={styles.loginForm}>
          <h1>登录</h1>
          <p>通过账号密码登录组织，或者切换为 <a href="#">学号密码登录</a></p>
          {error && <p className={styles.errorMessage}>{error}</p>}
          <form onSubmit={handleSubmit}>
            <div className={styles.formGroup}>
              <label htmlFor="username">用户名/邮箱</label>
              <input
                type="text"
                id="username"
                placeholder="请输入用户名/邮箱"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
              />
            </div>
            <div className={styles.formGroup}>
              <label htmlFor="password">登录密码</label>
              <input
                type="password"
                id="password"
                placeholder="请输入登录密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
              />
            </div>
            <button type="submit" className={styles.loginButton}>登录</button>
          </form>
          <div className={styles.loginLinks}>
            <p>或者 <a href="#" onClick={handleRegisterClick}>注册</a></p>
            <p><a href="#">忘记密码?</a></p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
